package com.lsl.bhllserver.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lsl.bhllserver.entity.*;
import com.lsl.bhllserver.service.order.*;
import com.lsl.bhllserver.service.product.ProductService;
import com.lsl.bhllserver.service.user.UserManageService;

@RestController
public class OrderController {

    @Autowired
    private BusOrderService busOrderService;

    @Autowired
    private CusOrderService cusOrderService;

    @Autowired
    private AdminOrderService adminOrderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private UserManageService userManageService;

    public boolean orderCheckOut(Map<String, String> data) {
        return cusOrderService.orderCheckOut(() -> {
            return new Order(
                    null,
                    Integer.parseInt(data.get("prodid")),
                    Integer.parseInt(data.get("cusid")),
                    Integer.parseInt(data.get("prodcount")),
                    0,
                    "",
                    null,
                    0,
                    null
                );
        });
    }

    //新增方法：完成订单（顾客确认收货）
    @RequestMapping(path = "/bhll/api/order/ok", method = RequestMethod.POST)
    public BoolResponse finishOrder(@RequestBody Map<String, String> data) {
        boolean flag = cusOrderService.finishOrder(() -> {
            Order targetOrder = new Order();
            targetOrder.setId(Integer.parseInt(data.get("orderid")));
            targetOrder.setCusId(Integer.parseInt(data.get("userid")));
            System.err.println("targetOrder: " + targetOrder.toString());
            return targetOrder;
        });
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/order/startPost", method = RequestMethod.POST)
    public BoolResponse startPost(@RequestBody Map<String, String> data) {
        boolean flag = busOrderService.startPost(() -> {
            Order targetOrder = new Order();
            targetOrder.setId(Integer.parseInt(data.get("orderid")));
            return targetOrder;
        });
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/order/finishPost", method = RequestMethod.POST)
    public BoolResponse finishPost(@RequestBody Map<String, String> data) {
        boolean flag = busOrderService.finishPost(() -> {
            Order targetOrder = new Order();
            targetOrder.setId(Integer.parseInt(data.get("orderid")));
            return targetOrder;
        });
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/order/edit", method = RequestMethod.POST)
    public BoolResponse editOrder(@RequestBody Map<String, String> data) {
        boolean flag = busOrderService.editPost(() -> {
            //Integer statusCode = busOrderService.getOrder(data.get("orderid")).getOrderStatus();
            Order temp = new Order();
            temp.setId(Integer.parseInt(data.get("orderid")));
            temp.setOrderPostman(data.get("postman"));
            temp.setOrderPostage(Integer.parseInt(data.get("postage")));
            return temp;
        });
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/order/delete", method = RequestMethod.POST)
    public BoolResponse deleteOrder(@RequestBody Map<String, String> data) {
        boolean flag = adminOrderService.deleteOrder(Integer.parseInt(data.get("orderid")));
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/order/problem", method = RequestMethod.POST)
    public BoolResponse problemOrder(@RequestBody Map<String, String> data) {
        boolean flag = cusOrderService.problemOrder(() -> {
            Order targetOrder = new Order();
            targetOrder.setId(Integer.parseInt(data.get("orderid")));
            targetOrder.setCusId(Integer.parseInt(data.get("userid")));
            return targetOrder;
        });
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/order/my", method = RequestMethod.POST)
    public OrderListResponse getMyOrders(@RequestBody Map<String, String> data) {
        List<Order> ol = null;
        List<Product> pl = new ArrayList<>();
        List<String> bl = new ArrayList<>();
        List<String> cl = new ArrayList<>();
        if (data.get("role").equals("customer")) {
            ol = cusOrderService.getMyOrder(Integer.parseInt(data.get("userid")));
            for (Order order : ol) {
                System.out.println(order.toString());
                pl.add(productService.getProductByID(order.getProdId()));
                bl.add(((Business) userManageService.findUser(
                        productService.getProductByID(
                                order.getProdId()).getBusId().toString(),
                        "business")).getBusName());
            }
            return new OrderListResponse(ol, pl, bl, null);
        } else if (data.get("role").equals("business")) {
            ol = busOrderService.getMyOrder(Integer.parseInt(data.get("userid")));
            for (Order order : ol) {
                pl.add(productService.getProductByID(order.getProdId()));
                cl.add(((Customer) userManageService.findUser(
                        order.getCusId().toString(),
                        "customer")).getCusName());
            }
            return new OrderListResponse(ol, pl, null, cl);
        } else {
            // List<Order> ol =
            // adminOrderService.getMyOrder(Integer.parseInt(data.get("userid")));
            return new OrderListResponse(null, null, null, null);
        }
    }

    @RequestMapping(path = "/bhll/api/order/search", method = RequestMethod.POST)
    public OrderListResponse searchOrders(@RequestBody Map<String, String> data) {
        // System.out.println(data.toString());
        HashSet<Order> ol = new HashSet<>();
        List<Product> pl = new ArrayList<>();
        List<String> bl = new ArrayList<>();
        List<String> cl = new ArrayList<>();
        for (Customer cus : getCusListByCusName(data.get("cusname"))) {
            for (Business bus : getBusListByBusName(data.get("busname"))) {
                ol.addAll(adminOrderService.searchOrder(new String[] {
                        data.getOrDefault("orderid", ""),
                        cus.getId().toString(),
                        bus.getId().toString(),
                        data.getOrDefault("postman", ""),
                        data.getOrDefault("status", "")
                }));
            }
        }
        for (Order order : ol) {
            pl.add(productService.getProductByID(order.getProdId()));
            cl.add(((Customer) userManageService.findUser(
                    order.getCusId().toString(),
                    "customer")).getCusName());
            bl.add(((Business) userManageService.findUser(
                    productService.getProductByID(
                            order.getProdId()).getBusId().toString(),
                    "business")).getBusName());
        }
        return new OrderListResponse(new ArrayList<>(ol), pl, bl, cl);
    }

    // 新增方法：根据ID获取订单信息（主要用于订单编辑页）
    @RequestMapping(path = "/bhll/api/order/get", method = RequestMethod.POST)
    public OrderInfoResponse getOrderInfo(@RequestBody Map<String, String> data) {
        Order order = busOrderService.getOrder(data.get("orderid"));
        Product product = productService.getProductByID(order.getProdId());
        Customer customer = (Customer) userManageService.findUser(
                order.getCusId().toString(),
                "customer");
        return new OrderInfoResponse (
            order, 
            product.getProdPrice() * order.getOrderBuyCount(), 
            customer.getCusName(), 
            customer.getCusPhone(), 
            customer.getCusAddress()
        );
    }

    @RequestMapping(path = "/bhll/api/order/getAll", method = RequestMethod.GET)
    public OrderListResponse getAllOrders() {
        List<Order> ol = null;
        List<Product> pl = new ArrayList<>();
        List<String> bl = new ArrayList<>();
        List<String> cl = new ArrayList<>();
        ol = adminOrderService.getAllOrder();
        for (Order order : ol) {
            pl.add(productService.getProductByID(order.getProdId()));
            cl.add(((Customer) userManageService.findUser(
                    order.getCusId().toString(),
                    "customer")).getCusName());
            bl.add(((Business) userManageService.findUser(
                    productService.getProductByID(
                            order.getProdId()).getBusId().toString(),
                    "business")).getBusName());
        }
        return new OrderListResponse(ol, pl, bl, cl);
    }

    /*
     * =============================================================================
     */

    /*
     * 内部辅助方法：用于通过顾客名获取订单
     */
    @SuppressWarnings("unchecked")
    private List<Customer> getCusListByCusName(String cusName) {
        if (cusName == null || cusName.isBlank()) {
            return (List<Customer>) userManageService.getAllUser("customer");
        }
        return (List<Customer>) userManageService.searchUser(new String[] {
                "", cusName, "", ""
        },
                "customer");
    }

    /*
     * 内部辅助方法：用于通过商家名获取订单
     */
    @SuppressWarnings("unchecked")
    private List<Business> getBusListByBusName(String busName) {
        if (busName == null || busName.isBlank()) {
            return (List<Business>) userManageService.getAllUser("business");
        }
        return (List<Business>) userManageService.searchUser(new String[] {
                "", busName, "", ""
        },
                "business");
    }

    /*
     * 内部类：返回布尔类型的响应
     */
    class BoolResponse {
        private String flag;

        public BoolResponse(String flag) {
            this.flag = flag;
        }

        public String getFlag() {
            return flag;
        }

        public void setFlag(String flag) {
            this.flag = flag;
        }
    }

    /*
     * 内部类：返回订单列表的响应
     */
    class OrderListResponse {
        private List<Order> ol;
        private List<Product> pl;
        private List<String> bl;
        private List<String> cl;

        public OrderListResponse(List<Order> ol, List<Product> pl, List<String> bl, List<String> cl) {
            this.ol = ol;
            this.pl = pl;
            this.bl = bl;
            this.cl = cl;
        }

        public List<Order> getOl() {
            return ol;
        }

        public void setOl(List<Order> ol) {
            this.ol = ol;
        }

        public List<Product> getPl() {
            return pl;
        }

        public void setPl(List<Product> pl) {
            this.pl = pl;
        }

        public List<String> getBl() {
            return bl;
        }

        public void setBl(List<String> bl) {
            this.bl = bl;
        }

        public List<String> getCl() {
            return cl;
        }

        public void setCl(List<String> cl) {
            this.cl = cl;
        }
    }

    /*
     * 内部类：返回订单详细信息的响应
     */
    class OrderInfoResponse {
        private Order order;
        private Integer orderPrice;
        private String cusName;
        private String cusPhone;
        private String cusAddress;

        public OrderInfoResponse(Order order, Integer orderPrice, String cusName, String cusPhone, String cusAddress) {
            this.order = order;
            this.orderPrice = orderPrice;
            this.cusName = cusName;
            this.cusPhone = cusPhone;
            this.cusAddress = cusAddress;
        }

        public Order getOrder() {
            return order;
        }

        public void setOrder(Order order) {
            this.order = order;
        }

        public Integer getOrderPrice() {
            return orderPrice;
        }

        public void setOrderPrice(Integer orderPrice) {
            this.orderPrice = orderPrice;
        }

        public String getCusName() {
            return cusName;
        }

        public void setCusName(String cusName) {
            this.cusName = cusName;
        }

        public String getCusPhone() {
            return cusPhone;
        }

        public void setCusPhone(String cusPhone) {
            this.cusPhone = cusPhone;
        }

        public String getCusAddress() {
            return cusAddress;
        }

        public void setCusAddress(String cusAddress) {
            this.cusAddress = cusAddress;
        }
    }
}
